<?php

namespace App\Http\Middleware;

use App\Exceptions\Fail;
use App\Http\Cache\AuthCache;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;

class AuthMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->header('authorize-token') ?? '';
        $user = AuthCache::getUser($token);
        AuthCache::setUser($token, $user);
        if ($user) {
            Context::add('user', $user);
            Context::add('token', $token);
        } else {
            throw new Fail('登录过期！', 20504);
        }
        return $next($request);
    }
}
